<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessContract;
use common\models\business\BusinessContractAdjustment;
use common\models\business\BusinessContractPurchase;
use common\models\business\BusinessContractStaPur;
use Yii;
use common\models\business\BusinessContractStatements;
use backend\modules\business\models\BusinessContractStatementsSearch;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * ContractStatementsController implements the CRUD actions for BusinessContractStatements model.
 */
class ContractStatementsController extends AdminController
{

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessContractStatements models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessContractStatementsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single BusinessContractStatements model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $adjust = (new  Query())->select('price,num,remark,number,id')
            ->addSelect(new Expression('FROM_UNIXTIME(createtime,"%Y-%m-%d")'))
            ->from(BusinessContractAdjustment::tableName())
            ->where(['contractid'=>$model->contract_id,'sta_id'=> $model->id])
            ->all();
        return $this->render('view', [
            'model' => $model,
            'adjust' => $adjust,
        ]);
    }

    /**
     * Creates a new BusinessContractStatements model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessContractStatements();


        if ($model->load(Yii::$app->request->post())) {
            $postdata = Yii::$app->request->post();

            //计算总数
            $gprice = array_key_exists('price',$postdata)?array_sum(ArrayHelper::getValue($postdata,'price')):0;
            $gnum = array_key_exists('num',$postdata)?array_sum(ArrayHelper::getValue($postdata,'num')):0;

            $aprice = array_key_exists('aprice',$postdata)?array_sum(ArrayHelper::getValue($postdata,'aprice')):0;
            $anum = array_key_exists('anum',$postdata)?array_sum(ArrayHelper::getValue($postdata,'anum')):0;

            //计算结算金额跟结算数量
            $model->price = floatval($gprice)+floatval($aprice);
            $model->num = floatval($gnum)+floatval($anum);

            //取出合同id
            if(!$model->save()){
                return $this->dialog($this->checkError($model));
            }


            //更新购进单与结算单的关系
            if(array_key_exists('purid',$postdata)) {
                BusinessContractPurchase::updateAll(['sta_id' => $model->id], ['id' => $postdata['purid']]);
            }
            //更新调整单与结算单的关系
            if(!empty($postdata['upajid'])) {
                BusinessContractAdjustment::updateAll(['sta_id' => $model->id], ['id' => $postdata['upajid']]);
            }



            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing BusinessContractStatements model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post())) {

            $postdata = Yii::$app->request->post();


            //计算总数
            $gprice = array_key_exists('price',$postdata)?array_sum(ArrayHelper::getValue($postdata,'price')):0;
            $gnum = array_key_exists('num',$postdata)?array_sum(ArrayHelper::getValue($postdata,'num')):0;

            $aprice = array_key_exists('aprice',$postdata)?array_sum(ArrayHelper::getValue($postdata,'aprice')):0;
            $anum = array_key_exists('anum',$postdata)?array_sum(ArrayHelper::getValue($postdata,'anum')):0;

            //计算结算金额跟结算数量
            $model->price = floatval($gprice)+floatval($aprice);
            $model->num = floatval($gnum)+floatval($anum);


            if(!$model->save()){
                return $this->dialog($this->checkError());
            }

            //更新购进单与结算单的关系
            if(array_key_exists('purid',$postdata)){
                $pidarr = $postdata['purid'];
                BusinessContractPurchase::updateAll(['sta_id'=>$model->id],['id'=>$pidarr]);
            }

            //更新调整单与结算单的关系
            if(array_key_exists('upajid',$postdata)) {
                BusinessContractAdjustment::updateAll(['sta_id' => $model->id], ['id' => $postdata['upajid']]);
            }
            //计算要删除的购进单
            $selfpid = ArrayHelper::getColumn(ArrayHelper::toArray($model->purchas),'id');
            $uppurid = array_key_exists('uppurid',$postdata) && $postdata['uppurid']?$postdata['uppurid']:[];
            $deletepidarr = array_diff($selfpid,$uppurid);
            BusinessContractPurchase::updateAll(['sta_id'=>0],['id'=>$deletepidarr]);

            //计算要删除的调整单
            $selfpid = ArrayHelper::getColumn(ArrayHelper::toArray($model->adjustment),'id');
            $upajid = array_key_exists('upajid',$postdata) && $postdata['upajid']?$postdata['upajid']:[];
            $deletepidarr = array_diff($selfpid,$upajid);
            BusinessContractAdjustment::updateAll(['sta_id'=>0],['id'=>$deletepidarr]);


            return $this->redirect(['view', 'id' => $model->id]);
        } else {

            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing BusinessContractStatements model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        Yii::$app->db->createCommand()->delete(BusinessContractStaPur::tableName(),'statements_id=:sid',[':sid'=>$id])->execute();

        return $this->redirect(['index']);
    }

    /**
     * Finds the BusinessContractStatements model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessContractStatements the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessContractStatements::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     * @param $id
     * 审核
     */
    public function actionAgree($id)
    {
        $data = [
            'agreeuser' => Yii::$app->user->identity->username,
            'agreetime' => time(),
            'status' => BusinessContractStatements::STATUS_AGREE
        ];
        $res = Yii::$app->db->createCommand()->update(BusinessContractStatements::tableName(),$data,'id=:id',[':id'=>$id])
            ->execute();
        return $this->dialog('审核通过');
    }


    /**
     * @return array
     * 获取购进单信息
     */
    public function actionPurprice()
    {
        $ids = Yii::$app->request->get('ids');
        $data = [];
        if(!empty($ids)){
            $purs = (new Query())->select('price,num')->from(BusinessContractPurchase::tableName())
                ->where(['id'=>$ids])
                ->all();


            $purprice = ArrayHelper::getColumn($purs,'price');
            $purnum = ArrayHelper::getColumn($purs,'num');
            $data['purprice'] = array_sum($purprice);
            $data['purnum'] = array_sum($purnum);
        }
        Yii::$app->response->format = Response::FORMAT_JSON;
        return $data;
    }


    /**
     * @return string
     * 取出指定合同可以结算的购进单
     */
    public function actionSearchPurchase()
    {
        $hasid = Yii::$app->request->post('selid')?Yii::$app->request->post('selid'):[];
        $contract_id = Yii::$app->request->post('contract_id')?Yii::$app->request->post('contract_id'):0;

        $query = (new Query())->select('*')->from(['pur'=>BusinessContractPurchase::tableName()])
            ->where('pur.contract_id=:contract_id and status=:agree and sta_id=\'\'',[':contract_id'=>$contract_id,':agree'=>BusinessContractStatements::STATUS_AGREE]);
        //去掉前台已经选择的购进单

        if(!empty($hasid)){
            $list = $query->andWhere(['not in','pur.id',$hasid])->all();
        }else{
            $list = $query->all();
        }

        if(empty($list)){
            return '没有可以结算的购机单';
        }

        //取出仔猪的成本
        foreach ($list as $key => $value){
            $list[$key]['createtime'] = date('Y-m-d',$value['createtime']);
            $list[$key]['status'] = BusinessContractPurchase::$statues[$value['status']];
        }
        $this->layout = false;

        return $this->render('_kucun',[
            'list' => $list
        ]);

    }




    /**
     * @return array
     * 获取选择的购进单的信息
     */
    public function actionGetPurchase()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $data = Yii::$app->request->post('data');
        $data = array_filter($data,function($item){
            return intval($item);
        });
        if(empty($data)){
            return ['data'=>[],'status'=>0];
        }

        $createtime = new Expression("FROM_UNIXTIME(createtime,'%y-%m-%d') as createtime");
        $list = (new Query())->select(['id','number','num','price','remark','status',$createtime])
            ->from(['pur'=>BusinessContractPurchase::tableName()])
            ->where(['id'=>$data])
            ->all();


        foreach ($list as $key => $value){
            $list[$key]['status'] = BusinessContractPurchase::$statues[$value['status']];
        }


        return $list;
    }



    /**
     * @return string
     * 取出指定合同可以结算的购进单
     */
    public function actionSearchAjest()
    {
        $hasid = Yii::$app->request->post('selid')?Yii::$app->request->post('selid'):[];
        $contract_id = Yii::$app->request->post('contract_id')?Yii::$app->request->post('contract_id'):0;

        $query = (new Query())->select('*')->from(['aj'=>BusinessContractAdjustment::tableName()])
            ->where('aj.contractid=:contract_id and status=:agree and sta_id=\'\'',[':contract_id'=>$contract_id,':agree'=>BusinessContractAdjustment::STATUS_AGREE]);

        //去掉前台已经选择的调整单
        if(!empty($hasid)){
            $list = $query->andWhere(['not in','aj.id',$hasid])->all();
        }else{
            $list = $query->all();
        }

        if(empty($list)){
            return '没有可以添加的调整单';
        }

        //构造数据格式
        foreach ($list as $key => $value){
            $list[$key]['createtime'] = date('Y-m-d',$value['createtime']);
        }
        $this->layout = false;

        return $this->render('_akucun',[
            'list' => $list
        ]);

    }


    /**
     * @return array
     * 获取选择的调整单的信息
     */
    public function actionGetAjest()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $data = Yii::$app->request->post('data');

        if(empty($data)){
            return ['data'=>[],'status'=>0];
        }

        $createtime = new Expression("FROM_UNIXTIME(createtime,'%y-%m-%d') as createtime");
        $list = (new Query())->select(['id','number','num','price','remark',$createtime])
            ->from(['pur'=>BusinessContractAdjustment::tableName()])
            ->where(['id'=>$data])
            ->all();

        return $list;
    }


}
